<template>
  <div class="app-container" v-loading="listLoading">
    <el-card class="filter-container" shadow="never">
      <div>
        <span class="info_title">Basic information</span>
        <el-button style="float:right" type="primary" @click="handleDelete()" size="small">
          Delete account
        </el-button>
        <el-button style="float:right;margin-right: 15px" @click="handleEidt()" type="primary" size="small">
          Edit data
        </el-button>
      </div>
      <div class="base_info_container">
        <div>
          <div><span class="second_title">Nickname:</span> {{ queryData.nickName }}</div>
          <div class="margin-top"><span class="second_title">Date of birth:</span>
            {{ formatCreateTime(queryData.birthday) }}</div>
          <div class="margin-top" v-if="queryData.gender === 1"><span class="second_title">Gender:</span> male</div>
          <div class="margin-top" v-else-if="queryData.gender === 2"><span class="second_title">Gender:</span> female
          </div>
          <div class="margin-top" v-else><span class="second_title">Gender:</span> unknown</div>

          <div class="margin-top" v-if="queryData.lookingFor === 1"><span class="second_title">Looking for:</span> male
          </div>
          <div class="margin-top" v-else-if="queryData.lookingFor === 2"><span class="second_title">Looking for:</span>
            female</div>
          <div class="margin-top" v-else><span class="second_title">Looking for:</span> unknown</div>
        </div>
        <div class="base_info_label_container">
          <div v-if="queryData.interests !== null && queryData.interests !== undefined">
            <span class="second_title">Interests:</span> {{ queryData.interests.join(",") }}
          </div>
          <div v-else><span class="second_title">interests:</span></div>
          <div class="margin-top"><span class="second_title">About me:</span> {{ queryData.aboutMe }}</div>
          <div class="margin-top"><span class="second_title">Why you here:</span>{{ queryData.socialPurposes}}</div>
        </div>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <div>
        <span class="info_title">Photo information</span>
      </div>
      <div class="user_img_container">
        <div class="base_info_content_container">
          <span>Avatar</span>
          <div class="wap-container" @mouseenter="enter(0, 0)" @mouseleave="leave(0, 0)">
            <img class="image" :src="avatar.avatarUrl" v-if="avatar.avatarUrl"
              @click="handlePictureCardPreview(avatar.avatarUrl)" />
            <div class="image_op_container" v-if="avatar.showOpe">
              <el-upload :on-change="(file, fileList) => { loadJsonFromFile(file, fileList, avatar.avatarUrl, 0) }"
                action="alert" :show-file-list="false" :auto-upload="false">
                <el-button size="mini" type="primary" icon="el-icon-edit" circle></el-button>
              </el-upload>
            </div>
          </div>
        </div>
        <div class="base_info_content_container">
          <span>Photo</span>
          <div class="wap-container" v-for="(item, index) in album" @mouseenter="enter(1, index)"
            @mouseleave="leave(1, index)">
            <img class="image" :src="item.imageUrl" @click="handlePictureCardPreview(item)" />
            <div class="image_op_container" v-if="item.showOpe">
              <el-upload :on-change="(file, fileList) => { loadJsonFromFile(file, fileList, item, 1) }" action="alert"
                :show-file-list="false" :auto-upload="false">
                <el-button size="mini" type="primary" icon="el-icon-edit" circle></el-button>
              </el-upload>
              <el-button size="mini" type="danger" class="image_op" style="margin-left:15px;" icon="el-icon-delete"
                @click="handleDeletePic(0, item, index)" circle></el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <div>
        <span class="info_title">Album information</span>
      </div>
      <div class="user_img_container">
        <div class="album_container">
          <span class="album_title">Public album</span>
          <div class="image_container">
            <div v-for="(item, index) in publicAlbum" @mouseenter="enter(2, index)" @mouseleave="leave(2, index)">
              <div class="wap-container">
                <video v-if="item.imageUrl.includes('.mp4')" class="image" :src="item.imageUrl"
                  @click="handlePictureCardPreview(item)">
                  <i class="el-icon-caret-right"></i>
                </video>
                <img v-else class="image" :src="item.imageUrl" @click="handlePictureCardPreview(item)" />
                <div class="image_op_container" v-if="item.showOpe">
                  <el-upload :on-change="(file, fileList) => { loadJsonFromFile(file, fileList, item, 2) }"
                    :auto-upload="false" action="alert" :show-file-list="false">
                    <el-button size="mini" type="primary" icon="el-icon-edit" circle></el-button>
                  </el-upload>
                  <el-button size="mini" type="danger" class="image_op" style="margin-left:15px;"
                    @click="handleDeletePic(1, item, index)" icon="el-icon-delete" circle></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="album_container">
          <span class="album_title">Private album</span>
          <div class="image_container">
            <div v-for="(item, index) in privateAlbum" @mouseenter="enter(3, index)"
              @mouseleave="leave(3, index)">
              <div class="wap-container">
                <video v-if="item.imageUrl.includes('.mp4')" class="image" :src="item.imageUrl"
                  @click="handlePictureCardPreview(item)">
                </video>
                <img v-else class="image" :src="item.imageUrl" @click="handlePictureCardPreview(item)" />
                <div class="image_op_container" v-if="item.showOpe">
                  <el-upload :on-change="(file, fileList) => { loadJsonFromFile(file, fileList, item, 3) }"
                    :auto-upload="false" action="alert" :show-file-list="false">
                    <el-button size="mini" type="primary" icon="el-icon-edit" circle></el-button>
                  </el-upload>
                  <el-button size="mini" type="danger" class="image_op" icon="el-icon-delete"
                    @click="handleDeletePic(2, item, index)" circle></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <div>
        <span class="info_title">Tunrn-ons</span>
      </div>
      <div class="tunrn_container">
        <span v-for="(item, index) in queryData.turnOnDtos" :key="index">
          {{item.turnOns}}{{index!==(queryData.turnOnDtos.length-1)?',':''}}
        </span>
      </div>
    </el-card>
    <el-dialog :visible.sync="dialogVisible" align="center">
      <div v-if="dialogImageUrl.includes('.mp4')">
        <video controls style="height:420px">
          <source :src="dialogImageUrl" type="video/mp4">
        </video>
      </div>
      <div v-else>
        <img style="height:420px" :src="dialogImageUrl" :zoom-rate="1.2" fit="cover" alt="Preview Image" />
        <!-- <el-image style="width: 500px; height: 500px" :src="dialogImageUrl"
                  :zoom-rate="1.2"
                  fit="cover"
                  alt="Preview Image"/> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { fetchModelDetail, fetchModelUpload, fetchModelDelete, fetchRemoveImage } from '@/api/model';
import { fetchList as fetchProductList } from '@/api/product';
import { formatDate } from '@/utils/date';

const defaultListQuery = {
  modeUserCode: null
};
const defaultRecommendOptions = [
  {
    label: '未推荐',
    value: 0
  },
  {
    label: '推荐中',
    value: 1
  }
];
export default {
  name: "hotProductList",
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      recommendOptions: Object.assign({}, defaultRecommendOptions),
      list: null,
      total: null,
      listLoading: false,
      queryData: {},
      dialogVisible: false,
      dialogImageUrl: "",
      multipleSelection: [],
      operates: [
        {
          label: "设为推荐",
          value: 0
        },
        {
          label: "取消推荐",
          value: 1
        },
        {
          label: "删除",
          value: 2
        }
      ],
      operateType: null,
      selectDialogVisible: false,
      dialogData: {
        list: null,
        total: null,
        multipleSelection: [],
        listQuery: {
          keyword: null,
          pageNum: 1,
          pageSize: 5
        }
      },
      sortDialogVisible: false,
      sortDialogData: { sort: 0, id: null },
      fileList: {

      },
      publicAlbum: [],
      privateAlbum: [],
      album: [],
      avatar: {
        avatarUrl: "",
        showOpe: false
      }
    };
  },
  created() {
    this.getModelDetail();
  },
  filters: {
    formatRecommendStatus(status) {
      if (status === 1) {
        return "推荐中";
      } else {
        return "未推荐";
      }
    }
  },
  methods: {
    formatCreateTime(time) {
      if (time !== null) {
        let date = new Date(time);
        return formatDate(date, 'yyyy/MM/dd')
      }
    },
    beforePicUpload(index, file) {
        var fileExt = file.name.replace(/.+\./,"").toLowerCase(); 
        const isPG = ["jpeg", "jpg","png"].indexOf(fileExt) !== -1
        const isVideo = ["mp4"].indexOf(fileExt) !== -1;
        const isLt2k = file.size / 1024 < 200;
        const isLt4k = file.size / 1024 < 400;
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (index == 0) {
          if (!isPG) {
            this.$message.error('Uploading images can only be in JPG or JPEG or PNG format!');
            return false;
          } else if (!isLt2k) {
            this.$message.error('Uploaded image size cannot exceed 200k!');
            return false;
          } else {
            return true;
          }
        } else if (index == 1) {
          if (!isPG) {
            this.$message.error('Uploading images can only be in JPG or JPEG or PNG format!');
            return false;
          } else if (!isLt4k) {
            this.$message.error('Uploaded image size cannot exceed 400k!');
            return false;
          } else {
            return true;
          }
        } else {
          if (!isPG && !isVideo) {
            this.$message.error('Uploading can only be in JPG or JPEG or PNG or MP4 format!');
            return false;
          } else{
            if (isPG) {
              if (!isLt4k) {
                this.$message.error('Uploaded image size cannot exceed 400k!');
                return false;
              }else{
                return true;
              }
            }else if(isVideo){
              if (!isLt10M) {
                this.$message.error('The uploaded video size cannot exceed 10M!');
                return false;
              }else{
                return true;
              }
            }
          }
        }
    },
    loadJsonFromFile(file, fileList, item, index) {
      if (this.beforePicUpload(index, fileList[0])) {
        const formData = new FormData();
        formData.append('file', fileList[0].raw);
        if (typeof (item) === "string") {
          formData.append('avatarFlag', "1");
          formData.append('imageCode', this.queryData.avatarImageCode);
        } else {
          formData.append('avatarFlag', "0");
          formData.append('imageCode', item.imageCode);
        }
        formData.append('modelUserCode', this.listQuery.modeUserCode);
        this.listLoading = true;
        fetchModelUpload(formData).then(response => {
          this.listLoading = false;
          this.getModelDetail();
        });
      }
    },
    enter(type, index) {
      if (type == 0) {
        this.avatar.showOpe = true;
      } else if (type == 1) {
        this.album[index].showOpe = true;
      } else if (type == 2) {
        this.publicAlbum[index].showOpe = true;
      } else if (type == 3) {
        this.privateAlbum[index].showOpe = true;
      }
    },
    leave(type, index) {
      if (type == 0) {
        this.avatar.showOpe = false;
      } else if (type == 1) {
        this.album[index].showOpe = false;
      } else if (type == 2) {
        this.publicAlbum[index].showOpe = false;
      } else if (type == 3) {
        this.privateAlbum[index].showOpe = false;
      }
    },

    modifyImage() {

    },
    handleDeletePic(type, item, index) {
      this.$confirm("Do you want to delete this photo?", "Prompt", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      }).then(() => {
        let params = {
          "imageCode": item.imageCode,
        }
        fetchRemoveImage(params).then(response => {
          if (type == 0) {
            this.$delete(this.album, index);
          } else if (type == 1) {
            this.$delete(this.publicAlbum, index);
          } else if (type == 2) {
            this.$delete(this.privateAlbum, index);
          }
        });
      })
    },
    handleRemove(uploadFile, uploadFiles) {
    },
    handlePictureCardPreview(uploadFile) {
      if (typeof (uploadFile) === "string") {
        this.dialogImageUrl = uploadFile;
      } else {
        this.dialogImageUrl = uploadFile.imageUrl
      }
      this.dialogVisible = true
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleRecommendStatusStatusChange(index, row) {
      this.updateRecommendStatusStatus(row.id, row.recommendStatus);
    },
    handleEidt() {
      this.$router.push({ path: '/modelEdit', query: { modelUserCode: this.$route.query.modelUserCode } })
    },
    handleDelete() {
      this.$confirm('Do you want to delete the Model account?', 'Prompt', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        let params = {
          "modeUserCode": this.listQuery.modeUserCode
        }
        fetchModelDelete(params).then(response => {
          this.$message({
            message: 'Successfully deleted！',
            type: 'success',
            duration: 1000
          });
          this.$router.go(-1);
        });
      })
    },
    handleSelectProduct() {
      this.selectDialogVisible = true;
      this.getDialogList();
    },
    handleSelectSearch() {
      this.getDialogList();
    },
    handleDialogSizeChange(val) {
      this.dialogData.listQuery.pageNum = 1;
      this.dialogData.listQuery.pageSize = val;
      this.getDialogList();
    },
    handleDialogCurrentChange(val) {
      this.dialogData.listQuery.pageNum = val;
      this.getDialogList();
    },
    handleDialogSelectionChange(val) {
      this.dialogData.multipleSelection = val;
    },
    handleSelectDialogConfirm() {
      if (this.dialogData.multipleSelection < 1) {
        this.$message({
          message: "请选择一条记录",
          type: "warning",
          duration: 1000
        });
        return;
      }
      let selectProducts = [];
      for (let i = 0; i < this.dialogData.multipleSelection.length; i++) {
        selectProducts.push({
          productId: this.dialogData.multipleSelection[i].id,
          productName: this.dialogData.multipleSelection[i].name
        });
      }
      this.$confirm("使用要进行添加操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {

      });
    },
    handleEditSort(index, row) {
      this.sortDialogVisible = true;
      this.sortDialogData.sort = row.sort;
      this.sortDialogData.id = row.id;
    },
    handleUpdateSort() {
      this.$confirm("是否要修改排序?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {

      });
    },
    getModelDetail() {
      this.listQuery.modeUserCode = this.$route.query.modelUserCode
      this.listLoading = true;
      const param = {
        "modeUserCode": this.listQuery.modeUserCode
      }
      fetchModelDetail(param).then(response => {
        this.listLoading = false;
        this.queryData = response.data;
        this.avatar.avatarUrl = response.data.avatarUrl;
        this.publicAlbum = response.data.publicAlbum;
        this.privateAlbum = response.data.privateAlbum;
        this.album = response.data.homeAlbum;
        this.addOpeField();
      });
    },
    addOpeField() {
      this.avatar.showOpe = false;
      if (this.album !== null) {
        this.album.forEach(element => {
          this.$set(element, 'showOpe', false)
        });
      }
      if (this.publicAlbum !== null) {
        this.publicAlbum.forEach(element => {
          this.$set(element, 'showOpe', false)
        });
      }
      if (this.privateAlbum !== null) {
        this.privateAlbum.forEach(element => {
          this.$set(element, 'showOpe', false)
        });
      }
    },
    updateRecommendStatusStatus(ids, status) {
      this.$confirm("是否要修改推荐状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = new URLSearchParams();
        params.append("ids", ids);
        params.append("recommendStatus", status);

      }).catch(() => {
        this.$message({
          type: "success",
          message: "已取消操作!"
        });
        this.getList();
      });
    },

    getDialogList() {
      fetchProductList(this.dialogData.listQuery).then(response => {
        this.dialogData.list = response.data.list;
        this.dialogData.total = response.data.total;
      });
    }
  },
}
</script>
<style>
.image {
  width: 100px;
  height: 100px;
  margin-left: 10px;
  margin-top: 5px;
  object-fit: cover;
}

.margin-top {
  margin-top: 10px;
}

.info_title {
  font-size: 20px;
  font-weight: bold;
}

.user_img_container {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.base_info_container {
  display: flex;
  margin-top: 20px;
}

.base_info_label_container {
  margin-left: 80px;
  max-width: 360px;
}

.base_info_content_container {
  display: flex;
  align-items: flex-start;
  margin-top: 20px;
}

.image_container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.album_container {
  display: flex;
  flex-direction: column;
  padding-top: 20px;
}

.album_title {
  margin-bottom: 10px;
}

.image_op_container {
  position: absolute;
  display: flex;
  justify-content: center;
  align-content: center;
  z-index: 100;
  width: 100px;
  margin-left: 10px;
  bottom: 5px;
}

.image_op {
  margin-left: 15px;
}

.wap-container {
  position: relative;
}

.second_title {
  font-weight: 500;
}
.tunrn_container{
  display: flex;
  margin-top:10px;
}
</style>
